package org.vt.scheduleapp;

import java.io.FileNotFoundException;
import java.io.IOException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.GregorianCalendar;
import java.util.List;
import java.util.Locale;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.text.format.DateFormat;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ArrayAdapter;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.ListView;

public class Schedule extends Activity implements OnClickListener
	{
		private static final String tag = "Schedule";
		private static final int TODO_ID = Menu.NONE;
		
		private Button selectedDayMonthYearButton;
		private Button currentMonth;
		private ImageView prevMonth;
		private ImageView nextMonth;
		private GridView calendarView;
		private GridCellAdapter adapter; 
		private Calendar _calendar;
		private int month, year;
		private static final String dateTemplate = "MMMM yyyy";

		
		
		/** Called when the activity is first created. */
		@Override
		public void onCreate(Bundle savedInstanceState)
			{
				super.onCreate(savedInstanceState);
				setContentView(R.layout.simple_calendar_view);

				
				
				_calendar = Calendar.getInstance(Locale.getDefault());
				month = _calendar.get(Calendar.MONTH) + 1;
				year = _calendar.get(Calendar.YEAR);
				Log.d(tag, "Calendar Instance:= " + "Month: " + month + " " + "Year: " + year);

				selectedDayMonthYearButton = (Button) this.findViewById(R.id.selectedDayMonthYear);

				prevMonth = (ImageView) this.findViewById(R.id.prevMonth);
				prevMonth.setOnClickListener(this);

				currentMonth = (Button) this.findViewById(R.id.currentMonth);
				currentMonth.setText(DateFormat.format(dateTemplate, _calendar.getTime()));

				nextMonth = (ImageView) this.findViewById(R.id.nextMonth);
				nextMonth.setOnClickListener(this);

				calendarView = (GridView) this.findViewById(R.id.calendar);

				// Initialized
				adapter = new GridCellAdapter(getApplicationContext(), R.id.calendar_day_gridcell, month, year);
				adapter.notifyDataSetChanged();
				calendarView.setAdapter(adapter);
			}
		
		public boolean onCreateOptionsMenu(Menu menu)
		{
			super.onCreateOptionsMenu(menu);
			menu.add(0, TODO_ID, 0, "To-Do List");
			return true;
			
		}
		
		public boolean onMenuItemSelected(int featureId, MenuItem item)
		{
			switch(item.getItemId())
			{
			case TODO_ID:
				startTodo();
				return true;
			}
			return super.onMenuItemSelected(featureId, item);
		}
		
		public void startTodo()
		{
			Intent i=new Intent(this, ToDoActivity.class);
			startActivityForResult(i, 0);
		}
		
		
		

		/**
		 * 
		 * @param month
		 * @param year
		 */
		private void setGridCellAdapterToDate(int month, int year)
			{
				adapter = new GridCellAdapter(getApplicationContext(), R.id.calendar_day_gridcell, month, year);
				_calendar.set(year, month - 1, _calendar.get(Calendar.DAY_OF_MONTH));
				currentMonth.setText(DateFormat.format(dateTemplate, _calendar.getTime()));
				adapter.notifyDataSetChanged();
				calendarView.setAdapter(adapter);
			}

		public void onClick(View v)
			{
				if (v == prevMonth)
					{
						if (month <= 1)
							{
								month = 12;
								year--;
							}
						else
							{
								month--;
							}
						Log.d(tag, "Setting Prev Month in GridCellAdapter: " + "Month: " + month + " Year: " + year);
						setGridCellAdapterToDate(month, year);
						
						
					}
				if (v == nextMonth)
					{
						if (month > 11)
							{
								month = 1;
								year++;
							}
						else
							{
								month++;
							}
						Log.d(tag, "Setting Next Month in GridCellAdapter: " + "Month: " + month + " Year: " + year);
						setGridCellAdapterToDate(month, year);
						
						
					}

			}

		@Override
		public void onDestroy()
			{
				Log.d(tag, "Destroying View ...");
				super.onDestroy();
			}

		
		// Inner Class
		public class GridCellAdapter extends BaseAdapter implements OnClickListener
			{
				private static final String tag = "GridCellAdapter";
				private final Context _context;

				private final List<String> list;
				private static final int DAY_OFFSET = 1;
				private final String[] weekdays = new String[]{"Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat"};
				private final String[] months = {"January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"};
				private final int[] daysOfMonth = {31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31};
				private int daysInMonth;
				private int currentDayOfMonth;
				private int currentWeekDay;
				private Button gridcell;
				private final SimpleDateFormat dateFormatter = new SimpleDateFormat("dd-MMM-yyyy");

				// Days in Current Month
				public GridCellAdapter(Context context, int textViewResourceId, int month, int year)
					{
						super();
						this._context = context;
						this.list = new ArrayList<String>();
						Log.d(tag, "==> Passed in Date FOR Month: " + month + " " + "Year: " + year);
						Calendar calendar = Calendar.getInstance();
						setCurrentDayOfMonth(calendar.get(Calendar.DAY_OF_MONTH));
						setCurrentWeekDay(calendar.get(Calendar.DAY_OF_WEEK));
						Log.d(tag, "New Calendar:= " + calendar.getTime().toString());
						Log.d(tag, "CurrentDayOfWeek :" + getCurrentWeekDay());
						Log.d(tag, "CurrentDayOfMonth :" + getCurrentDayOfMonth());

						// Print Month
						printMonth(month, year);

					}
				private String getMonthAsString(int i)
					{
						return months[i];
					}

				private String getWeekDayAsString(int i)
					{
						return weekdays[i];
					}

				private int getNumberOfDaysOfMonth(int i)
					{
						return daysOfMonth[i];
					}

				public String getItem(int position)
					{
						return list.get(position);
					}

				public int getCount()
					{
						return list.size();
					}

				/**
				 * Prints Month
				 * 
				 * @param mm
				 * @param yy
				 */
				private void printMonth(int mm, int yy)
					{
						Log.d(tag, "==> printMonth: mm: " + mm + " " + "yy: " + yy);
						// The number of days to leave blank at
						// the start of this month.
						int trailingSpaces = 0;
						int daysInPrevMonth = 0;
						int prevMonth = 0;
						int prevYear = 0;
						int nextMonth = 0;
						int nextYear = 0;

						int currentMonth = mm - 1;
						String currentMonthName = getMonthAsString(currentMonth);
						daysInMonth = getNumberOfDaysOfMonth(currentMonth);

						Log.d(tag, "Current Month: " + " " + currentMonthName + " having " + daysInMonth + " days.");

						// Gregorian Calendar : MINUS 1, set to FIRST OF MONTH
						GregorianCalendar cal = new GregorianCalendar(yy, currentMonth, 1);
						Log.d(tag, "Gregorian Calendar:= " + cal.getTime().toString());

						if (currentMonth == 11)
							{
								prevMonth = currentMonth - 1;
								daysInPrevMonth = getNumberOfDaysOfMonth(prevMonth);
								nextMonth = 0;
								prevYear = yy;
								nextYear = yy + 1;
								Log.d(tag, "*->PrevYear: " + prevYear + " PrevMonth:" + prevMonth + " NextMonth: " + nextMonth + " NextYear: " + nextYear);
							}
						else if (currentMonth == 0)
							{
								prevMonth = 11;
								prevYear = yy - 1;
								nextYear = yy;
								daysInPrevMonth = getNumberOfDaysOfMonth(prevMonth);
								nextMonth = 1;
								Log.d(tag, "**--> PrevYear: " + prevYear + " PrevMonth:" + prevMonth + " NextMonth: " + nextMonth + " NextYear: " + nextYear);
							}
						else
							{
								prevMonth = currentMonth - 1;
								nextMonth = currentMonth + 1;
								nextYear = yy;
								prevYear = yy;
								daysInPrevMonth = getNumberOfDaysOfMonth(prevMonth);
								Log.d(tag, "***---> PrevYear: " + prevYear + " PrevMonth:" + prevMonth + " NextMonth: " + nextMonth + " NextYear: " + nextYear);
							}

						// Compute how much to leave before before the first day of the
						// month.
						// getDay() returns 0 for Sunday.
						int currentWeekDay = cal.get(Calendar.DAY_OF_WEEK) - 1;
						trailingSpaces = currentWeekDay;

						Log.d(tag, "Week Day:" + currentWeekDay + " is " + getWeekDayAsString(currentWeekDay));
						Log.d(tag, "No. Trailing space to Add: " + trailingSpaces);
						Log.d(tag, "No. of Days in Previous Month: " + daysInPrevMonth);

						if (cal.isLeapYear(cal.get(Calendar.YEAR)) && mm == 2)
							{
								++daysInMonth;
							}

						// Trailing Month days
						for (int i = 0; i < trailingSpaces; i++)
							{
								Log.d(tag, "PREV MONTH:= " + prevMonth + " => " + getMonthAsString(prevMonth) + " " + String.valueOf((daysInPrevMonth - trailingSpaces + DAY_OFFSET) + i));
								list.add(String.valueOf((daysInPrevMonth - trailingSpaces + DAY_OFFSET) + i) + "-GREY" + "-" + getMonthAsString(prevMonth) + "-" + prevYear);
							}

						// Current Month Days
						for (int i = 1; i <= daysInMonth; i++)
							{
								Log.d(currentMonthName, String.valueOf(i) + " " + getMonthAsString(currentMonth) + " " + yy);
								if (i == getCurrentDayOfMonth())
									{
										list.add(String.valueOf(i) + "-BLUE" + "-" + getMonthAsString(currentMonth) + "-" + yy);
									}
								else
									{
										list.add(String.valueOf(i) + "-WHITE" + "-" + getMonthAsString(currentMonth) + "-" + yy);
									}
							}

						// Leading Month days
						for (int i = 0; i < list.size() % 7; i++)
							{
								Log.d(tag, "NEXT MONTH:= " + getMonthAsString(nextMonth));
								list.add(String.valueOf(i + 1) + "-GREY" + "-" + getMonthAsString(nextMonth) + "-" + nextYear);
							}
					}

		

				public long getItemId(int position)
					{
						return position;
					}

				public View getView(int position, View convertView, ViewGroup parent)
					{
						View row = convertView;
						if (row == null)
							{
								LayoutInflater inflater = (LayoutInflater) _context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
								row = inflater.inflate(R.layout.calendar_day_gridcell, parent, false);
							}

						// Get a reference to the Day gridcell
						gridcell = (Button) row.findViewById(R.id.calendar_day_gridcell);
						gridcell.setOnClickListener(this);

						// ACCOUNT FOR SPACING

						Log.d(tag, "Current Day: " + getCurrentDayOfMonth());
						String[] day_color = list.get(position).split("-");
						String theday = day_color[0];
						String themonth = day_color[2];
						String theyear = day_color[3];

						// Set the Day GridCell
						gridcell.setText(theday);
						gridcell.setTag(theday + "-" + themonth + "-" + theyear);
						Log.d(tag, "Setting GridCell " + theday + "-" + themonth + "-" + theyear);

						if (day_color[1].equals("GREY"))
							{
								gridcell.setTextColor(Color.LTGRAY);
							}
						if (day_color[1].equals("WHITE"))
							{
								gridcell.setTextColor(Color.WHITE);
							}
						if (day_color[1].equals("BLUE"))
							{
								gridcell.setTextColor(getResources().getColor(R.color.static_text_color));
							}
						return row;
					}
				
				
				public void onClick(final View view)
					{
						
						
						final String date_month_year = (String) view.getTag(); //returns the name of the date clicked

						selectedDayMonthYearButton.setText(date_month_year); //sets the day clicked in a text box on the top of the calendar
						
						final ListView myList = (ListView) findViewById(R.id.eventlist); //gets the ListView of events
						
						EventReader reader = new EventReader(Schedule.this); //reader for all the events
						
						List<CalendarEvent> event = new ArrayList<CalendarEvent>(); //puts all the events in a arraylist
						try {
							event = reader.getAllEvents();
						} catch (FileNotFoundException e1) {
							
							e1.printStackTrace();
						} catch (IOException e1) {
							
							e1.printStackTrace();
						}
						
						//Storage containers for the various elements of an event\
						
						final ArrayList<String> eventName = new ArrayList<String>(); 
						final ArrayList<String> startDay = new ArrayList<String>();
						final ArrayList<String> endDay = new ArrayList<String>();
						final ArrayList<String> startTime = new ArrayList<String>();
						final ArrayList<String> endTime = new ArrayList<String>();
					
						String[] startDate = new String[3]; //picks apart relevant info about the startDate for easy comparison
								
						eventName.add("+ add event");				
						for(CalendarEvent e : event)
						{
							String newStartDate = e.getStartDate().replaceAll("\\s", ""); //get rid of all white space
							startDate = newStartDate.split("/");
						
							String startMonth = startDate[0];
							String eventStartDay = startDate[1];
							String startYear = startDate[2];
						
							
							int getMonthNumber = Integer.parseInt(startMonth); //converts string month into an int 
							
							String startMonthName =  getMonthAsString(getMonthNumber - 1); //converts the number - 1, since months are stored starting at 0,
																						   //to the string representation i.e. 1 = January
							
							//creates a string thats formated the same as the previously created tag for each day
							String compareDate = eventStartDay + "-" + startMonthName + "-" + startYear; 

							if(compareDate.equals(date_month_year)) //if the event start day matches the day clicked tag then the event info is populated
							{
								eventName.add(e.getName());
								startDay.add(e.getStartDate());
								endDay.add(e.getEndDate());
								startTime.add(e.getStartTime());
								endTime.add(e.getEndTime());
							}
						}
						
						
						//array adapter for the ListView of events
						ArrayAdapter<String> eventList = new ArrayAdapter<String>(Schedule.this,
								android.R.layout.simple_list_item_1, android.R.id.text1, eventName);
						myList.setAdapter(eventList);
						
						//listener for clicking on different events
						myList.setOnItemClickListener(new OnItemClickListener() {							
							public void onItemClick(AdapterView<?> parent, final View view,
									final int position, long id) {
								
								final String nameOfEvent = eventName.get(position);
											
								//if + add event is clicked the user is taken to the add event menu
								if(myList.getItemAtPosition(position).equals("+ add event"))
								{
									Intent i = new Intent(view.getContext(), AddEventActivity.class);
									
									Log.v("HERE", "here");
									//Relevant information about the event is sent with the intent
									i.putExtra("eventName", "");
									
									//gets the info about the start Day to send with the intent for editing
									String[] startDateForIntent = date_month_year.split("-");
									String eventStartDay = startDateForIntent[0];
									String startMonth = startDateForIntent[1];
									
									//the month is given in string form and is desired in integer form. the following converts the month to its integer
									//i.e. January = 0;
									int startMonthNum;
									for(startMonthNum = 0; startMonthNum < months.length; startMonthNum++){
										
										if(startMonth.equals(months[startMonthNum])){
											startMonthNum++;
											break;
											}
										}
									String finalStartMonth = ""+ startMonthNum;
									
									String startYear = startDateForIntent[2];
									
									String startHour = "0";
									String startMin = "0";
									String endHour = "0";
									String endMin = "0";
									
																		
									i.putExtra("startYear", startYear);
									i.putExtra("startMonth", finalStartMonth);
									i.putExtra("startDay", eventStartDay);
									
									i.putExtra("endYear", startYear);
									i.putExtra("endMonth", finalStartMonth);
									i.putExtra("endDay", eventStartDay);
									
									i.putExtra("startHour", startHour);
									i.putExtra("startMin", startMin);	
									
									i.putExtra("endHour", endHour);
									i.putExtra("endMin", endMin);
									
									startActivityForResult(i, 0);
								}
								else //if the user clicks on any other event they will be asked if they want to edit that event
								{
																		
								
									AlertDialog.Builder alert = new AlertDialog.Builder(Schedule.this);
									alert.setTitle("Would you like to edit this event?");

									alert.setPositiveButton("Ok", new DialogInterface.OnClickListener(){
										public void onClick(DialogInterface dialog, int whichButton) {
				
											//gets the info about the start Day to send with the intent for editing
											String[] startDateForIntent = startDay.get(position - 1).split("/");
											final String startMonth = startDateForIntent[0];
											final String eventStartDay = startDateForIntent[1];
											final String startYear = startDateForIntent[2];
											
											//gets the info about the end Day to send with the intent for editing
											String[] endDateForIntent = endDay.get(position - 1).split("/");
											final String endMonth = endDateForIntent[0];
											final String eventEndDay = endDateForIntent[1];
											final String endYear = endDateForIntent[2];
											
											//gets the info about the start time to send with the intent for editing
											String[] startTimeForIntent = startTime.get(position - 1).split(":");
											final String startHour = startTimeForIntent[0];
											final String startMin = startTimeForIntent[1];
										
											
											//gets the info about the end time to send with the intent for editing
											String[] endTimeForIntent = startTime.get(position - 1).split(":");
											final String endHour = endTimeForIntent[0];
											final String endMin = endTimeForIntent[1];
											
											Intent i = new Intent(view.getContext(),AddEventActivity.class);

											//Relevant information about the event is sent with the intent
											i.putExtra("eventName", nameOfEvent);
											
											i.putExtra("startYear", startYear);
											i.putExtra("startMonth", startMonth);
											i.putExtra("startDay", eventStartDay);
										
											i.putExtra("endYear", endYear);
											i.putExtra("endMonth", endMonth);
											i.putExtra("endDay", eventEndDay);
											
											i.putExtra("startHour", startHour);
											i.putExtra("startMin", startMin);	
											
				
											i.putExtra("endHour", endHour);
											i.putExtra("endMin", endMin);
										
											startActivityForResult(i, 0);
										}
									});

									alert.setNegativeButton("Cancel", new DialogInterface.OnClickListener(){
										public void onClick(DialogInterface dialog, int whichButton){
											return;
										}
									});

									alert.show();
								}

							}
						});
			
						try
							{
								Date parsedDate = dateFormatter.parse(date_month_year);
								Log.d(tag, "Parsed Date: " + parsedDate.toString());
							}
						catch (ParseException e)
							{
								e.printStackTrace();
							}
						
							
					}

				public int getCurrentDayOfMonth()
					{
						return currentDayOfMonth;
					}

				private void setCurrentDayOfMonth(int currentDayOfMonth)
					{
						this.currentDayOfMonth = currentDayOfMonth;
					}
				public void setCurrentWeekDay(int currentWeekDay)
					{
						this.currentWeekDay = currentWeekDay;
					}
				public int getCurrentWeekDay()
					{
						return currentWeekDay;
					}
			}
	}
